package operate

import (
	"database/sql"
	"fmt"
	"go.manyji.com/lib/app"
	"go.manyji.com/lib/formatStruct"
	"go.manyji.com/lib/log"
	"sieve_proc/data"
	"sync"
	"time"
)

type order_interface interface {
	GetTagId() string
	loopTaskData()
	doTaskData() error
	updateTag(string)
	GetId() int
}

var (
	localOrderLock    = sync.Mutex{}
	localTaskOrderIds = make(map[string]order_interface)
)

func AddOrderTaskId(orderInfo order_interface) {
	localOrderLock.Lock()
	defer localOrderLock.Unlock()
	if _, ok := localTaskOrderIds[orderInfo.GetTagId()]; ok {
		return
	}
	localTaskOrderIds[orderInfo.GetTagId()] = orderInfo
	app.AsyncSafe(orderInfo.loopTaskData)

}
func RemoveOrderTaskId(TagId string) {
	localOrderLock.Lock()
	defer localOrderLock.Unlock()
	delete(localTaskOrderIds, TagId)
}

func init() {
	data.AfterDBConnect(func() {
		for _t, _ := range wsfMap {
			func(k string) {
				app.Async(func() {
					loopWsTaskData(k)
				})
			}(_t)
		}
	})
}

func loopWsTaskData(tag string) {
ForEnd:
	for {
		select {
		case <-app.CTX.Done():
			break ForEnd
		default:
			checkWsTaskData(tag)
		}
		time.Sleep(time.Second * 1)
	}
}
func getTableName(tag string) string {
	if _tab, ok := wsfMap[tag]; ok {
		return _tab
	}
	return ""
}
func checkWsTaskData(tag string) {
	rows, err := data.DB().Query(fmt.Sprintf("SELECT %s from %s where status>=1 and status<=2 order by id asc limit ?", formatStruct.ParseStructFields(&Op_Order{}).ColsToString(), getTableName(tag)), *orderCnt)
	if err != nil {
		if err != sql.ErrNoRows {
			log.Err("checkWsfTaskData", err)
		}
		return
	}
	defer rows.Close()
	for rows.Next() {
		info := &Op_Order{}
		err = rows.Scan(formatStruct.ParseStructFields(info).GetPtrs()...)
		if err != nil {
			continue
		}
		info.updateTag(tag)
		err = info.doTaskData()
		if err == nil {
			AddOrderTaskId(info)
		} else {
			log.Err(info, err)
		}
	}
}
